package com.ccrc.websocket;

import java.io.IOException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * WebSocket 消息推送服务类
 * 
 * @author Jspider
 * 
 *         2014-11-18 下午7:53:13
 */
@ServerEndpoint(value = "/seajs/webclient")
public class ChatAnnotation {

	private static final Log log = LogFactory.getLog(ChatAnnotation.class);

	private static final String GUEST_PREFIX = "Guest";
	private static final AtomicInteger connectionIds = new AtomicInteger(0);
	private static final Map<String, Object> connections = new HashMap<String, Object>();
	private static final ConcurrentHashMap<String, List<String>> signalMap = new ConcurrentHashMap<>();

	private final String nickname;
	private Session session;
	

	public ChatAnnotation() {
		nickname = GUEST_PREFIX + connectionIds.getAndIncrement();
	}

	@OnOpen
	public void start(Session session) {
		this.session = session;
		connections.put(nickname, this);

	}

	@OnClose
	public void end() {
		connections.remove(this);
		String message = String.format("* %s %s", nickname, "has disconnected.");
		broadcast(message);
	}

	/**
	 * 消息发送触发方法
	 * 
	 * @param message
	 */
	@OnMessage
	public void incoming(String message) {
		JSONObject json = JSONObject.fromObject(message);
		System.out.println(json);
		if (json.containsKey("id") && json.containsKey("ope")) {
			String id = json.getString("id");
			String ope = json.getString("ope");
			if (signalMap.get(this.nickname) == null) {
				signalMap.put(this.nickname, new ArrayList<String>());
			}
			if (signalMap.get(this.nickname).contains(id)) {
				if (ope.equals("-")) {
					signalMap.get(this.nickname).remove(id);
				}
			} else {
				if (ope.equals("+")) {
					signalMap.get(this.nickname).add(id);
				}
			}
		}

		JSONArray jsonArray = new JSONArray();
		JSONObject jsonObject = null;
		jsonArray.clear();
		System.out.println("loop...");
		if (signalMap.get(nickname) == null) {
			signalMap.put(nickname, new ArrayList<>());
		}
		if (!signalMap.get(nickname).isEmpty()) {
			for (String item : signalMap.get(nickname)) {
				jsonObject = new JSONObject();
				jsonObject.put("id", item);
				jsonObject.put("xValue", new Date().getTime());
				NumberFormat format = new DecimalFormat("##.##");
				jsonObject.put("yValue", format.format( Math.random() * 10));
				jsonArray.add(jsonObject);
			}
			if (!jsonArray.isEmpty()) {
				System.out.println(jsonArray);
				broadcast(jsonArray.toString());
			}
		}
	}

	@OnError
	public void onError(Throwable t) throws Throwable {
		log.error("Chat Error: " + t.toString(), t);
	}

	/**
	 * 消息发送方法
	 * 
	 * @param msg
	 */
	private static void broadcast(String msg) {
		/*
		 * if (msg.indexOf("Guest0") != -1) { sendUser(msg); } else {
		 * sendAll(msg); }
		 */
		sendAll(msg);
	}

	/**
	 * 向所有用户发送
	 * 
	 * @param msg
	 */
	public static void sendAll(String msg) {
		for (String key : connections.keySet()) {
			ChatAnnotation client = null;
			try {
				client = (ChatAnnotation) connections.get(key);

				synchronized (client) {
					client.session.getBasicRemote().sendText(msg);
				}
			} catch (IOException e) {
				log.debug("Chat Error: Failed to send message to client", e);
				connections.remove(client);
				try {
					client.session.close();
				} catch (IOException e1) {
					// Ignore
				}
				/*
				 * String message = String.format("* %s %s", client.nickname,
				 * "has been disconnected.");
				 * 
				 * broadcast(message);
				 */
			}
		}
	}

	/**
	 * 向指定用户发送消息
	 * 
	 * @param msg
	 */
	public static void sendUser(String msg) {
		ChatAnnotation c = (ChatAnnotation) connections.get("Guest0");
		try {
			c.session.getBasicRemote().sendText(msg);
		} catch (IOException e) {
			log.debug("Chat Error: Failed to send message to client", e);
			connections.remove(c);
			try {
				c.session.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			String message = String.format("* %s %s", c.nickname, "has been disconnected.");
			broadcast(message);
		}
	}
}
